package com.laolang.shop.modules.auth.handler;

import cn.hutool.core.util.StrUtil;
import com.laolang.shop.common.core.consts.ModuleNameConst;
import com.laolang.shop.common.core.domain.SimpleAjax;
import com.laolang.shop.common.core.util.LogUtil;
import com.laolang.shop.common.core.util.PrintJsonWriter;
import com.laolang.shop.modules.auth.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // khl 日志记录
        LogUtil.warn(log, ModuleNameConst.AUTH, StrUtil.format("越权操作,userId:{} url:{}", SecurityUtil.getUserId(), httpServletRequest.getRequestURI()));
        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        PrintJsonWriter.printJson(httpServletResponse, SimpleAjax.forbid());
    }
}
